import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';
import { FastifyRequest } from 'fastify';
import { Observable } from 'rxjs';

@Injectable()
export class LoginGuard implements CanActivate {
  constructor(
    private readonly reflector: Reflector,
    private readonly jwtService: JwtService,
  ) { }
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const request: FastifyRequest = context.switchToHttp().getRequest();
    const notRequireLogin = this.reflector.getAllAndOverride('not-require-login', [
      context.getClass(),
      context.getHandler()
    ]);

    if (notRequireLogin) return true

    const authorization = request.headers.authorization;

    if (!authorization) {
      throw new UnauthorizedException('用户未登录');
    }

    try {
      const verifyUser = this.jwtService.verify(authorization);
      // 将用户id添加到请求体中，方便在控制器中使用
      if (verifyUser && request.body) {
        (request.body as any).userId = verifyUser.userId;
      }
      return true;
    } catch (e) {

      throw new UnauthorizedException('token失效，请重新登录');
    }
  }
}
